package cn.edu.tju.elm.service;

import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.repository.UserRepository;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.exception.ForbiddenException;
import cn.edu.tju.elm.exception.MethodArgumentNotValidException;
import cn.edu.tju.elm.exception.DataNotFoundException;
import cn.edu.tju.elm.model.DTO.BusinessDTO;
import cn.edu.tju.elm.utils.ObjectUtils;
import cn.edu.tju.elm.model.entity.Business;
import cn.edu.tju.elm.repository.BusinessRepository;
import com.fasterxml.jackson.databind.util.BeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class BusinessService {
//    @Autowired
    private final BusinessRepository businessRepository;
    private final UserRepository userRepository;
    private final UserService userService;

    public BusinessService(BusinessRepository businessRepository, UserRepository userRepository, UserService userService) {
        this.businessRepository = businessRepository;
        this.userRepository = userRepository;
        this.userService = userService;
    }

    public List<Business> listBusinessesByToken(){
        User nowUser = userService.getUserWithAuthorities();

        List<Business> businesses = businessRepository.findAllByBusinessOwner(nowUser);
        if(businesses.isEmpty()){
            throw(new DataNotFoundException("资源未找到：该用户暂无店铺"));
        }else{
            return businesses;
        }
    }

    public Business addBusiness(Business newBusiness){
        User nowUser = userService.getUserWithAuthorities();
        LocalDateTime now = LocalDateTime.now();

        if(newBusiness.getBusinessOwner()==null){
            newBusiness.setBusinessOwner(nowUser);
        }

        if(newBusiness.getStartPrice()==null){
            newBusiness.setStartPrice(BigDecimal.ZERO);
        }

        if(newBusiness.getDeliveryPrice()==null){
            newBusiness.setDeliveryPrice(BigDecimal.ZERO);
        }

        newBusiness.setCreateTime(now);
        newBusiness.setCreator(nowUser.getId());
        newBusiness.setUpdateTime(now);
        newBusiness.setUpdater(nowUser.getId());
        newBusiness.setDeleted(false);

        return businessRepository.save(newBusiness);
    }

    public Business getBusinessById(Long id){
        Business existingBusiness = businessRepository.findById(id)
                .orElseThrow(() -> new DataNotFoundException("资源未找到：店铺不存在"));;
        return existingBusiness;
    }

    public Business updateBusiness(Long id, BusinessDTO businessDTO) {
        Business existingBusiness = businessRepository.findById(id)
                .orElseThrow(() -> new MethodArgumentNotValidException("请求参数非法：店铺不存在"));

        User nowUser = userService.getUserWithAuthorities();
        User existingUser = existingBusiness.getBusinessOwner();
        if(!existingUser.equals(nowUser)){
            throw new ForbiddenException("权限不足：用户非店铺所有者");
        }
        BeanUtils.copyProperties(businessDTO,existingBusiness);

        LocalDateTime now = LocalDateTime.now();
        existingBusiness.setUpdateTime(now);
        existingBusiness.setUpdater(nowUser.getId());

        // 3. 调用 save()（此时 existingUser 是 managed 状态，save() 触发 UPDATE）
        return businessRepository.save(existingBusiness);
    }

    public Business patchBusiness(Long id, BusinessDTO businessDTO){
        // 1. 查询数据库中的原始实体
        Business existingBusiness = businessRepository.findById(id)
                .orElseThrow(() -> new MethodArgumentNotValidException("请求参数非法：店铺不存在"));

        User nowUser = userService.getUserWithAuthorities();
        User existingUser = existingBusiness.getBusinessOwner();
        if(!existingUser.equals(nowUser)){
            throw new ForbiddenException("权限不足：用户非店铺所有者");
        }


        // 2. 用前端数据覆盖原始实体的字段
        if(!(businessDTO.getBusinessAddress() ==null)){
            existingBusiness.setBusinessAddress(businessDTO.getBusinessAddress());
        }
        if(!(businessDTO.getBusinessImg() ==null)){
            existingBusiness.setBusinessImg(businessDTO.getBusinessImg());
        }
        if(!(businessDTO.getBusinessExplain() ==null)){
            existingBusiness.setBusinessExplain(businessDTO.getBusinessExplain());
        }
        if(!(businessDTO.getBusinessName() ==null)){
            existingBusiness.setBusinessName(businessDTO.getBusinessName());
        }
        if(!(businessDTO.getDeliveryPrice() ==null)){
            existingBusiness.setDeliveryPrice(businessDTO.getDeliveryPrice());
        }
        if(!(businessDTO.getRemarks() ==null)){
            existingBusiness.setRemarks(businessDTO.getRemarks());
        }
        if(!(businessDTO.getOrderTypeId() ==null)){
            existingBusiness.setOrderTypeId(businessDTO.getOrderTypeId());
        }
        if(!(businessDTO.getStartPrice() ==null)){
            existingBusiness.setStartPrice(businessDTO.getStartPrice());
        }

        LocalDateTime now = LocalDateTime.now();
        existingBusiness.setUpdateTime(now);
        existingBusiness.setUpdater(nowUser.getId());

        // 3. 调用 save()（此时 existingUser 是 managed 状态，save() 触发 UPDATE）
        return businessRepository.save(existingBusiness);
    }

    public Business deleteBusiness(Long id){
        Business existingBusiness = businessRepository.findById(id)
                .orElseThrow(() -> new DataNotFoundException("资源未找到：店铺不存在"));
        User nowUser = userService.getUserWithAuthorities();
        if(!existingBusiness.getBusinessOwner().equals(nowUser)){
            throw new ForbiddenException("权限不足：仅店铺所属人可删除店铺");
        }

        // businessRepository.deleteById(id);

        // 逻辑删除
        existingBusiness.setDeleted(true);
        User updater = userService.getUserWithAuthorities();
        LocalDateTime now = LocalDateTime.now();
        existingBusiness.setUpdateTime(now);
        existingBusiness.setUpdater(updater.getId());

        return businessRepository.save(existingBusiness);
    }

    public List<Business> listBusinessesByType(Integer type) {
        List<Business> businesses = businessRepository.findAllByOrderTypeId(type);
        if(businesses.isEmpty()){
            throw new DataNotFoundException("资源未找到：店铺不存在");
        }
        return businesses;
    }

}
